package org.example.edusmart.controller.Login;

import org.example.edusmart.pojo.UserPojo;
import org.example.edusmart.pojo.UserRolePojo;
import org.example.edusmart.request.login.RegisterPojo;
import org.example.edusmart.service.UserService;
import org.example.edusmart.utils.Authorization;
import org.example.edusmart.utils.RedisUtils;
import org.example.edusmart.utils.Result;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class RegisterController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private Authorization authorization;

    /**
     * 用户注册
     *
     * @param user 前端传递值
     * @return 状态码以及相关信息
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/register/")
    public Result register(@RequestBody @NotNull RegisterPojo user) {
        //校验用户名是否重复
        UserPojo i = userService.checkUserByUsername(user.getUsername());
        if (i != null && i.getUsername() != null) {
            return new Result(404, "用户名已存在，请登录账号或替换名称");
        }
        //校验密码
        if (!user.getPassword().equals(user.getVerifyPassword())) {
            return new Result(404, "两次密码输入不一致");
        }
        //校验邮箱是否重复
        UserPojo a = userService.checkEmail(user.getEmail());
        if (a != null && a.getEmail() != null) {
            return new Result(404, "邮箱已存在，请替换邮箱");
        }
        //从redis中取出邮箱的对应验证码
        String verifyCode = redisUtils.getValue(user.getEmail());
        if (!user.getCode().equals(verifyCode)) {
            return new Result(404, "验证码输入错误或验证码已过期");
        }
        //校验身份
        if ("学生".equals(user.getIdentify())) {
            HashMap<String, Object> params = new HashMap<>() {{
                put("username", user.getUsername());
                put("studentNumber", user.getNumber());
            }};
            HashMap<String, Object> studentAuthorization = authorization.getStudentAuthorization(params);
            if (studentAuthorization != null && "200".equals(String.valueOf(studentAuthorization.get("code")))) {
                // 有返回值，并且状态码为200，说明校验通过，先存入数据库后进行赋权
                extracted(user);
                //根据用户名查用户id，并把用户id插入用户角色表内
                UserPojo student = userService.checkUserByUsername(user.getUsername());
                UserRolePojo userRole = new UserRolePojo();
                userRole.setUserId(String.valueOf(student.getUserId()));
                userRole.setRoleId("2");// 2在角色表中代表学生身份
                userService.insertUserRole(userRole);
                //插入完成后即完成赋权，把该用户的学工号插入对应数据表中
                HashMap<String, Object> insertData = new HashMap<>() {{
                    put("username", user.getUsername());
                    put("email", user.getEmail());
                    put("number", user.getNumber());
                }};
                userService.insertNumber(insertData);
            } else {// 没有完成校验，即为游客身份，赋权
                return getResult(user);
            }
        }
        if ("教师".equals(user.getIdentify())) {
            HashMap<String, Object> params = new HashMap<>() {{
                put("username", user.getUsername());
                put("teacherNumber", user.getNumber());
            }};
            HashMap<String, Object> teacherAuthorization = authorization.getTeacherAuthorization(params);
            if (teacherAuthorization != null && "200".equals(String.valueOf(teacherAuthorization.get("code")))) {
                extracted(user);
                UserPojo teacher = userService.checkUserByUsername(user.getUsername());
                UserRolePojo userRole = new UserRolePojo();
                userRole.setUserId(String.valueOf(teacher.getUserId()));
                userRole.setRoleId("1");// 1在角色表中代表教师身份
                userService.insertUserRole(userRole);
                HashMap<String, Object> insertData = new HashMap<>() {{
                    put("username", user.getUsername());
                    put("email", user.getEmail());
                    put("number", user.getNumber());
                }};
                userService.insertNumber(insertData);
            } else {
                return getResult(user);
            }
        }
        return new Result(200, "注册成功");
    }

    /**
     * 给校验失败赋为游客
     * @param user 前端传值
     * @return 状态码
     */
    @NotNull
    private Result getResult(@RequestBody @NotNull RegisterPojo user) {
        extracted(user);//存进数据库
        UserPojo visitor = userService.checkUserByUsername(user.getUsername());
        UserRolePojo userRole = new UserRolePojo();
        userRole.setUserId(String.valueOf(visitor.getUserId()));
        userRole.setRoleId("3");// 3在角色表中代表游客身份
        userService.insertUserRole(userRole);
        return new Result(200, "注册成功，认证失败，为游客身份");
    }

    /**
     * 新增用户操作
     * @param user 入参
     */
    private void extracted(RegisterPojo user) {
        HashMap<String, Object> insertParameter = new HashMap<>() {{
            put("username", user.getUsername());
            put("email", user.getEmail());
            put("password", bCryptPasswordEncoder.encode(user.getPassword())); //密码加密
            put("avatar",user.getAvatar());//头像
        }};
        userService.addUser(insertParameter);
    }
}
